#include <copydir.h>
//AB同时同步
void twoway_syn(char *path1, char *path2, struct file_rate *filerate) {
	struct file_quality ch1[D_LEN],ch2[D_LEN];
	
	int d_len1 = q_directory(path1,ch1);
	int d_len2 = q_directory(path2,ch2);
	int i = 0,j = 0;
	char pathname1[D_SIZE];
	char pathname2[D_SIZE];

	while(d_len1 != i && d_len2 != j) {
		if(strcmp(ch1[i].name,ch2[j].name) < 0) {
			sprintf(pathname1,"%s/%s",path1,ch1[i].name);
			sprintf(pathname2,"%s/%s",path2,ch1[i].name);
			if(ch1[i].type == 1)		backup_directory(pathname1, pathname2, filerate);
			else if(ch1[i].type == 2)	copy_file(pathname1, pathname2);
			else if(ch1[i].type == 3)	mkfifo(pathname2, 0666);
			else				continue;
			i++;
			filerate->sum++;
			pthread_t ptid;
			pthread_create(&ptid, NULL, putout_rate, filerate);
        		pthread_join(ptid,NULL);
		} else if(strcmp(ch1[i].name,ch2[j].name) > 0) {
			sprintf(pathname2,"%s/%s",path2,ch2[j].name);
			sprintf(pathname1,"%s/%s",path1,ch2[j].name);
			if(ch1[j].type == 1)		backup_directory(pathname1, pathname2, filerate);
			else if(ch1[j].type == 2)	copy_file(pathname2, pathname1);
			else if(ch1[j].type == 3)	mkfifo(pathname1, 0666);
			else				continue;
			j++;
		} else {
			sprintf(pathname1,"%s/%s",path1,ch1[i].name);
			sprintf(pathname2,"%s/%s",path2,ch2[j].name);
			if(ch1[i].type == 1) {
				twoway_syn(pathname1, pathname2, filerate);
			} else if(ch1[i].type == 2) {
				if(strcmp(ch1[i].time, ch2[j].time) > 0)
					copy_file(pathname1, pathname2);
				else if(strcmp(ch1[i].time, ch2[j].time) < 0)
					copy_file(pathname2, pathname1);
			}
			i++;
			j++;
			filerate->sum++;
			pthread_t ptid;
			pthread_create(&ptid, NULL, putout_rate, filerate);
        		pthread_join(ptid,NULL);
		}
	}
	while(i < d_len1) {
		sprintf(pathname1,"%s/%s",path1,ch1[i].name);
		sprintf(pathname2,"%s/%s",path2,ch1[i].name);
		if(ch1[i].type == 1)		backup_directory(pathname1, pathname2, filerate);
		else if(ch1[i].type == 2)	copy_file(pathname1, pathname2);
		else if(ch1[i].type == 3)	mkfifo(pathname2, 0666);
		else				continue;
		i++;
		filerate->sum++;
		pthread_t ptid;
		pthread_create(&ptid, NULL, putout_rate, filerate);
		pthread_join(ptid,NULL);
	}
	while(j < d_len2) {
		sprintf(pathname2,"%s/%s",path2,ch2[j].name);
		sprintf(pathname1,"%s/%s",path1,ch2[j].name);
		if(ch1[j].type == 1)		backup_directory(pathname1, pathname2, filerate);
		else if(ch1[j].type == 2)	copy_file(pathname2, pathname1);
		else if(ch1[j].type == 3)	mkfifo(pathname1, 0666);
		else				continue;
		j++;
	}
	FILE *f = fopen("./pro_copy.log","a+");
	time_t rawtime;
	struct tm *timeinfo;
	timeinfo = localtime(&rawtime);
	fprintf(f,"\007The current date/time is:%s\n",asctime(timeinfo));
	fprintf(f,"twoway %s --> %s\n",path1, path2);
	fclose(f);	
}


